package com.game.net.client.jpbsocket;

import com.game.message.Msg;
import com.game.message.connetion.ConnectionManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ChannelHandler.Sharable
public class JPbSocketNettyClientHandler extends SimpleChannelInboundHandler<Msg> {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private ChannelHandlerContext ctx;
    private boolean isConnect = false;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        logger.info("channel active...");
        this.ctx = ctx;
        this.isConnect = true;
    }

    public ChannelHandlerContext getCtx() {
        return ctx;
    }

	/**
     * 当收到消息时，原样转发给链接的player
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Msg msg) throws Exception {
        int userId = msg.getUserId();
        ConnectionManager.getInstance().writeMessage(userId,msg);
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        this.isConnect = false;
    }

    public boolean isConnect() {
        return isConnect;
    }
}
